package com.million.msmservice.controller;

import com.million.msmservice.service.TengXunSmsService;
import com.million.msmservice.utils.RandomUtil;
import com.million.commonutils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @Author: studyboy
 * @Date: 2022/4/2  22:37
 * 用来做短信管理
 */
@Api(tags = "短信管理")
@RestController
@RequestMapping("/edumsm/msm")
public class TengXunSmsController {

    @Autowired
    private TengXunSmsService tengXunSmsService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //使用腾讯云发送手机短信验证码
    @ApiOperation("获取验证码")
    @GetMapping("sendMsm/{phone}")
    public R sendMsm (@PathVariable("phone") String phone) {

        if (!StringUtils.isEmpty(phone)) {
            //1.从redis 中获取验证码，如果获取到直接返回
            String code = redisTemplate.opsForValue().get(phone);
            if (!StringUtils.isEmpty(code)) {
                return R.ok();
            }
            //2.如果redis获取不到，就进行腾讯云发送
            code = RandomUtil.getFourBitRandom();
            boolean isSend = tengXunSmsService.sendMsm(phone, code);
            if (isSend) {
                //如果发送成功
                //就写入到缓存中  设置2分钟有效时长
                redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
                return R.ok();
            } else {
                return R.error().message("发送短信失败");
            }
        } else {
            return R.error().message("手机号不能为空");
        }
    }
}
